package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.feginclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcMenuMapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author: Hes
 * @description 密码认证实现
 * @date: 2023/6/26 11:31
 */
@Slf4j
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {
    @Autowired
    XcUserMapper xcUserMapper;
    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    CheckCodeClient checkCodeClient;

    /**
     * 密码认证
     *
     * @param authParamsDto 认证参数
     * @return
     */
    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //验证码验证
//        String checkcode = authParamsDto.getCheckcode();
//        String checkcodekey = authParamsDto.getCheckcodekey();
//        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
//        if (StringUtils.isBlank(checkcodekey) || StringUtils.isBlank(checkcode)) {
//            throw new RuntimeException("验证码为空");
//        }
//        if (!verify) {
//            throw new RuntimeException("验证码输入错误，请重新输入");
//        }
        //密码验证
        String username = authParamsDto.getUsername();
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
        if (xcUser == null) {
            return null;
        }
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser, xcUserExt);
        String passwordForm = authParamsDto.getPassword();
        String passwordDB = xcUser.getPassword();
        //加密的密码比对,第一个参数是没有加密的，第二个参数是加密的
        boolean matches = passwordEncoder.matches(passwordForm, passwordDB);
        if (!matches) {
            throw new RuntimeException("用户名或者密码错误");
        }
        return xcUserExt;
    }
}
